package com.hrpc.channelHandler.handler;

import com.hrpc.enumeration.ResponseCode;
import com.hrpc.exceptions.RespCodeException;
import com.hrpc.hRpcBootStarp;
import com.hrpc.loadbalancer.LoadBalancer;
import com.hrpc.protection.CircuitBreaker;
import com.hrpc.transport.message.hRpcRequest;
import com.hrpc.transport.message.hRpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 这是一个用来测试的类
 */
public class MySimpleChannelInboundHandler extends SimpleChannelInboundHandler<hRpcResponse> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, hRpcResponse hRpcResponse) throws Exception {
        //从全局的挂起的请求中寻找与之匹配的待处理的completeFuture
        CompletableFuture<Object> completableFuture = hRpcBootStarp.PENDING_REQUEST.get(hRpcResponse.getRequestId());
        Map<SocketAddress, CircuitBreaker> everyIpCircuitBreaker =
                hRpcBootStarp.getInstance().getConfiguration().getEveryIpCircuitBreaker();
        SocketAddress socketAddress = channelHandlerContext.channel().remoteAddress();
        CircuitBreaker circuitBreaker = everyIpCircuitBreaker.get(channelHandlerContext.channel().remoteAddress());
        byte code = hRpcResponse.getCode();
        if (code == ResponseCode.FAIL.getCode()){//客户端失败
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            throw new RespCodeException(code,ResponseCode.FAIL.getDesc());
        }else if(code == ResponseCode.RATE_LIMIT.getCode()){//限流
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            throw new RespCodeException(code,ResponseCode.RATE_LIMIT.getDesc());
        }else if(code == ResponseCode.RESOURCE_NOT_FOUND.getCode()){//服务未发现
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            throw new RespCodeException(code,ResponseCode.RESOURCE_NOT_FOUND.getDesc());
        }else if (code == ResponseCode.SUCCESS.getCode()) {//成功
            //服务提供方给的结果
            Object returnValue = hRpcResponse.getBody();
            //TODO 需要针对响应码code做处理
            returnValue = returnValue == null ? new Object() : returnValue;
            completableFuture.complete(returnValue);
        }else if (code == ResponseCode.SUCCESS_HEART_BEAT.getCode()){
            completableFuture.complete(null);
        }else if (code == ResponseCode.CLOSING.getCode()){
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            //修正负载均衡器
                //1.从健康列表中移除
            hRpcBootStarp.CHANNEL_CACHE.remove(socketAddress);
                //2.找到负载均衡器进行reLoadBalance
            LoadBalancer load_balancer = hRpcBootStarp.getInstance().getConfiguration().getLoad_balancer();
            //重新进行负载均衡
            hRpcRequest hRpcRequest = hRpcBootStarp.REQUEST_THREAD_LOCAL.get();
            load_balancer.reLoadBalance(hRpcRequest.getRequestPayload().getInterfaceName(),
                    hRpcBootStarp.CHANNEL_CACHE.keySet().stream().toList());
            throw new RespCodeException(code,ResponseCode.CLOSING.getDesc());
        }
    }
}
